﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;

public class Player1Controller : MonoBehaviour
{
    GameBoard gameBoard;
    Vector2 modify = new Vector2(0f, -1f);

    public float speed = 4f;
    public float speedFactor = 1f;

    private Rigidbody2D rb2d;

    float moveX;
    float moveY;
    Animator animator;


    private void stop()
    {
        animator.SetFloat("Mag", 0f);        
    }

    private void Awake()
    {
        animator = gameObject.GetComponent<Animator>();
        rb2d = gameObject.GetComponent<Rigidbody2D>();
        gameBoard = GameObject.Find("Board").GetComponent<GameBoard>();
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Debug.Log(transform.position);
        if (Input.GetKeyDown(KeyCode.K)) {
            gameBoard.SendMessage("buildBlock", transform.position);
        }
    }

    private void FixedUpdate()
    {
        //moveX = Input.GetAxisRaw("Horizontal");
        //moveY = Input.GetAxisRaw("Vertical");
        moveX = (Input.GetKey(KeyCode.D) ? 1.0f : 0.0f) - (Input.GetKey(KeyCode.A) ? 1.0f : 0.0f);
        moveY = (Input.GetKey(KeyCode.W) ? 1.0f : 0.0f) - (Input.GetKey(KeyCode.S) ? 1.0f : 0.0f);

        Vector2 moveVec = SquareToCircle(moveX, moveY);

        rb2d.transform.position += speed * speedFactor * Time.fixedDeltaTime * new Vector3(moveVec.x, moveVec.y, 0);

        if (moveX != 0 || moveY != 0)
        {
            animator.SetFloat("X", moveX);
            animator.SetFloat("Y", moveY);
        }
        animator.SetFloat("Mag", moveY * moveY + moveX * moveX);
    }

    Vector2 SquareToCircle(float x, float y)
    {
        Vector2 output = Vector2.zero;
        output.x = x * Mathf.Sqrt(1 - (y * y) / 2);
        output.y = y * Mathf.Sqrt(1 - (x * x) / 2);
        return output;
    }
}
